<?php

namespace backend\modules\languages\models;

use Yii;

/**
 * This is the model class for table "{{%languages}}".
 *
 * @property int $id
 * @property string $code
 * @property string $title
 * @property string $title_native
 * @property string $sef
 * @property string $image
 * @property string $description
 * @property string $metakey
 * @property string $metadesc
 * @property string $sitename
 * @property int $published
 * @property int $ordering
 */
class Languages extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%languages}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['code', 'title', 'title_native', 'sef'], 'required'],
            [['metakey', 'metadesc'], 'string'],
            [['published', 'ordering'], 'integer'],
            [['code'], 'string', 'max' => 7],
            [['title', 'title_native', 'sef', 'image'], 'string', 'max' => 50],
            [['description'], 'string', 'max' => 512],
            [['sitename'], 'string', 'max' => 1024],
            [['sef'], 'unique'],
            [['code'], 'unique']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('mod_langs', 'ID'),
            'code' => Yii::t('mod_langs', 'LANGUAGE_TAG'),
            'title' => Yii::t('mod_langs', 'TITLE'),
            'title_native' => Yii::t('mod_langs', 'NATIVE_TITLE'),
            'sef' => Yii::t('mod_langs', 'URL_LANGUAGE_CODE'),
            'image' => Yii::t('mod_langs', 'IMAGE'),
            'description' => Yii::t('mod_langs', 'DESCRIPTION'),
            'metakey' => Yii::t('mod_langs', 'META_KEY'),
            'metadesc' => Yii::t('mod_langs', 'META_DESC'),
            'sitename' => Yii::t('mod_langs', 'CUSTOM_SITE_NAME'),
            'published' => Yii::t('mod_langs', 'STATUS'),
            'ordering' => Yii::t('mod_langs', 'ORDER'),
        ];
    }

    /**
     * 语言列表
     * @param array $firstItem 第一项数组，如：[''=>'请选择语言']
     * @param string $key 语言键值
     * @param string $value 语言显示的值
     * @return array 返回所有有效的语言数组
     */
    public static function getList($firstItem = null, $key = 'code', $value = 'title_native')
    {
        $languages = static::find()
            ->where(['published' => 1])
            ->orderBy('ordering')
            ->all();

        if ($firstItem === null){
            $firstItem = ['*' => Yii::t('mod_langs', 'ALL_LANGUAGES')];
        }

        $langList = [];
        foreach ($languages as $lang) {
            $langList[$lang->$key] = $lang->$value;
        }

        return array_merge($firstItem, $langList);
    }

}
